﻿// Copyright (c) Inossem. All rights reserved.
// Licensed under the LGPL-3.0 license. See LICENSE file in the project root for full license information.
using DWF.Studio.RemoteCtrls.Custom;
using DWF.Studio.RemoteCtrls.Models;
using DWF.Studio.RemoteCtrls.Proxy;
using DWF.Studio.RemoteCtrls.Services;
using DWF.Studio.Share.Log;
using System;
using System.Collections.Generic;
using System.Collections.ObjectModel;
using System.ComponentModel;
using System.Data;
using System.Linq;
using System.Runtime.InteropServices;
using System.Text;
using System.Threading.Tasks;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Controls.Primitives;
using System.Windows.Data;
using System.Windows.Documents;
using System.Windows.Input;
using System.Windows.Interop;
using System.Windows.Media;
using System.Windows.Media.Imaging;
using System.Windows.Navigation;
using System.Windows.Shapes;
using System.Xml.Linq;

namespace DWF.Studio.RemoteCtrls.SearchExporer
{
    /// <summary>
    /// UCtrlSearchExporer.xaml 的交互逻辑
    /// </summary>
    public partial class UCtrlSearchExporer : UserControl
    {
        private ObservableCollection<Models.SearchActivityModel> _obsSelectResult = new ObservableCollection<Models.SearchActivityModel>();

        private static double windowWidth = 0;
        /// <summary>
        /// 选中活动
        /// </summary>
        public Action<ShowSearchActivityEventArgs> _selectionChanged = null;

        private List<string> ProjectFile = new List<string>();
        public UCtrlSearchExporer()
        {
            InitializeComponent();
            if (!DesignerProperties.GetIsInDesignMode(this))
            {
                init();
            }
        }

        private void init()
        {
            popupSearchBox.CustomPopupPlacementCallback = new CustomPopupPlacementCallback(placePopup);
            _obsSelectResult.Clear();
            this.searchListbox.ItemsSource = _obsSelectResult;
        }
        #region 查询
        public CustomPopupPlacement[] placePopup(Size popupSize, Size targetSize, Point offset)
        {
            var width = windowWidth / 2 - 600;
            CustomPopupPlacement[] ttplaces = new CustomPopupPlacement[] {
                new CustomPopupPlacement(new Point(width, 65), PopupPrimaryAxis.Vertical),
                new CustomPopupPlacement(new Point(400, 65), PopupPrimaryAxis.Vertical)
            };
            return ttplaces;
        }
        public void ShowSearchBox(List<string> listFile, double mainWindowWidth)
        {
            UCtrlSearchExporer.windowWidth = mainWindowWidth;
            popupSearchBox.IsOpen = false;
            popupSearchBox.IsOpen = true;
            IntPtr handle = GetHwnd(popupSearchBox);
            SetFocus(handle);
            _obsSelectResult.Clear();
            ProjectFile.Clear();
            ProjectFile = listFile;
            TextBox txtSearchBox = WPFExtensionMethods.FindVisualChild<TextBox>(FindName("txtSearch") as DependencyObject);
            Keyboard.Focus(txtSearchBox);
            var tempGrid = txtSearch.Template.FindName("searchCTGrid", txtSearch) as Grid;
            var tempTxt = tempGrid.FindName("Uc_TblShow") as TextBlock;
            tempTxt.Text = LocalizationProvider.GetLocalizedString("UCtrlSearchExplorer_text_Search");
        }
        /// <summary>
        /// 捕捉键盘事件
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void UserControl_PreviewKeyDown(object sender, KeyEventArgs e)
        {
            if (popupSearchBox.IsOpen == true)
            {
                if (e.Key == Key.Escape)
                {
                    popupSearchBox.IsOpen = false;
                    clearSearchTextBox();
                }
                else if (e.Key==Key.Up)
                {
                    int index = this.searchListbox.SelectedIndex;

                    if (index == -1)//没选中
                    {
                        searchListbox.SelectedIndex = 0;
                        return;
                    }
                    else if (index > 0)
                    {
                        searchListbox.SelectedIndex = index - 1;
                    }
                }
                else if (e.Key == Key.Down)
                {
                    int index = searchListbox.SelectedIndex;

                    if (index == -1) //没选中
                    {
                        searchListbox.SelectedIndex = 0;
                        return;
                    }
                    else if (index < searchListbox.Items.Count - 1)
                    {
                        searchListbox.SelectedIndex = index + 1;
                    }
                }
                else if (e.Key == Key.Enter)
                {
                    if (this.searchListbox.SelectedItem != null)
                    {
                        var searchActivityModel = this.searchListbox.SelectedItem as SearchActivityModel;
                       
                        if (searchActivityModel != null)
                        {
                            _selectionChanged?.Invoke(new ShowSearchActivityEventArgs(searchActivityModel.FullName, searchActivityModel.IdRef, searchActivityModel.DisplayName));
                            popupSearchBox.IsOpen = false;
                            clearSearchTextBox();
                        }
                    }
                }
            }
        }
        private void ClearSearchBtn_Click(object sender, RoutedEventArgs e)
        {
            clearSearchTextBox();
        }
        private void popupSearchBox_Closed(object sender, EventArgs e)
        {
            clearSearchTextBox();
        }
        /// <summary>
        /// 清空搜索框
        /// </summary>
        private void clearSearchTextBox()
        {
            TextBox txtSearchBox = WPFExtensionMethods.FindVisualChild<TextBox>(FindName("txtSearch") as DependencyObject);
            txtSearchBox.Text = string.Empty;
        }
        
        /// <summary>
        /// 文本框文字改变
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void txtSearch_TextChanged(object sender, TextChangedEventArgs e)
        {
            if (popupSearchBox.IsOpen == true)
            {
                WPFExtensionMethods.Debounce(1000, null, new Action(() => { loadSearchListbox(); }),this);
            }
        }
        private void loadSearchListbox()
        {
            this.searchListbox.Dispatcher.Invoke((Action)(() =>
            {
                string searchTxt = WPFExtensionMethods.FindVisualChild<TextBox>(FindName("txtSearch") as DependencyObject).Text;
                _obsSelectResult.Clear();
                var listSearchActivity = new List<SearchActivityModel>();
                foreach (string item in ProjectFile)
                {
                    //搜索文件内容
                    var result = WPFExtensionMethods.SearchActivityByDisplayName(searchTxt,item, System.IO.Path.GetFileName(item));
                    
                    if (result != null && !string.IsNullOrWhiteSpace(searchTxt))
                    {
                        result.ToList().ForEach(p => _obsSelectResult.Add(p));
                    }
                }
                if (_obsSelectResult.Count == 0)
                {
                    var searchActivityModel = new SearchActivityModel();
                    searchActivityModel.DisplayName = LocalizationProvider.GetLocalizedString("UCtrlSearchExporer_ListBox_NoResults");
                    searchActivityModel.xElementType = XElementType.Empty;
                    _obsSelectResult.Add(searchActivityModel);
                }
            }));
        }
        
        /// <summary>
        /// 点击查找目标
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void searchListbox_SelectionChanged(object sender, SelectionChangedEventArgs e)
        {
            if (this.searchListbox.SelectedItem != null)
            {
                if ((this.searchListbox.SelectedItem as SearchActivityModel).xElementType == XElementType.Empty)
                {
                    return;
                }

                else
                {
                    var searchItem = this.searchListbox.SelectedItem;
                }
            }
        }
        private void searchListbox_PreviewMouseDoubleClick(object sender, MouseButtonEventArgs e)
        {
            
            var searchActivityModel = this.searchListbox.SelectedItem as SearchActivityModel;
            if (string.IsNullOrWhiteSpace(searchActivityModel.IdRef))
                return;
            TextBox txtSearchBox = WPFExtensionMethods.FindVisualChild<TextBox>(FindName("txtSearch") as DependencyObject);
            //因为加载事件 第二次打开搜索框会闪一下所以加判断
            if (popupSearchBox.IsOpen == true && !string.IsNullOrWhiteSpace(txtSearchBox.Text))
            {
                popupSearchBox.IsOpen = false;
                clearSearchTextBox();
            }
            if (searchActivityModel != null)
            {
                _selectionChanged?.Invoke(new ShowSearchActivityEventArgs(searchActivityModel.FullName, searchActivityModel.IdRef, searchActivityModel.DisplayName));
                popupSearchBox.IsOpen = false;
                clearSearchTextBox();
            }
        }
        #endregion

        #region popup输入法光标定位
        [DllImport("User32.dll")]
        public static extern IntPtr SetFocus(IntPtr hWnd);

        IntPtr GetHwnd(Popup popup)
        {
            HwndSource source = (HwndSource)PresentationSource.FromVisual(popup.Child);
            return source.Handle;
        }
        #endregion
    }
}
